package io.hellsinger.vortex.ui.screen.storage.list

import android.content.Context
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout.LayoutParams.MATCH_PARENT
import android.widget.FrameLayout.LayoutParams.WRAP_CONTENT
import androidx.recyclerview.widget.RecyclerView
import io.hellsinger.navigation.screen.ListScreenController
import io.hellsinger.theme.vortex.VortexSettings
import io.hellsinger.vortex.R
import io.hellsinger.vortex.data.model.PathItem
import io.hellsinger.vortex.di.StorageListDependencies
import io.hellsinger.vortex.domain.model.Transition
import io.hellsinger.vortex.domain.repository.StorageRepository
import io.hellsinger.vortex.navigation.findDependencies
import io.hellsinger.vortex.ui.component.adapter.ItemAdapter
import io.hellsinger.vortex.ui.component.adapter.Items
import io.hellsinger.vortex.ui.component.adapter.UnsupportedViewTypeException
import io.hellsinger.vortex.ui.component.adapter.listener.ItemListener
import io.hellsinger.vortex.ui.component.dp
import io.hellsinger.vortex.ui.component.drawable.RoundedCornerDrawable
import io.hellsinger.vortex.ui.component.dsl.buildMenu
import io.hellsinger.vortex.ui.component.item.divider.DividerItemView
import io.hellsinger.vortex.ui.component.item.drawer.DrawerItemView
import io.hellsinger.vortex.ui.component.item.title.TitleItemView
import io.hellsinger.vortex.ui.component.item.twoline.TwoLineItemView
import io.hellsinger.vortex.ui.dsl.frameParams
import io.hellsinger.vortex.ui.screen.storage.create.StorageCreateItemScreenController
import io.hellsinger.vortex.ui.screen.storage.create.StorageCreateItemScreenController.Args.ParentPath
import io.hellsinger.vortex.ui.screen.storage.detail.StorageItemDetailScreenController
import io.hellsinger.vortex.ui.screen.storage.rename.StorageRenameItemScreenController
import io.hellsinger.vortex.ui.screen.storage.transaction.StorageTransactionScreenController
import io.hellsinger.vortex.ui.screen.storage.transaction.StorageTransactionScreenController.Args.Companion.LOAD_TYPE_DELETE
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch

internal class StorageListMenuScreenController(
    private val context: Context,
) : ListScreenController<List<PathItem>>(),
    ItemListener {
    private var repository: StorageRepository? = null

    private val scope = CoroutineScope(Dispatchers.Main.immediate + SupervisorJob())

    override val usePopupMode: Boolean
        get() = true

    override fun onBackActivatedImpl(): Boolean = false

    override val adapter =
        ItemAdapter(
            listener = this,
            viewProvider = { parent, viewType ->
                when (viewType) {
                    Items.TWO_LINE ->
                        TwoLineItemView(parent.context).apply {
                            setTitleColor(VortexSettings.colors { key_storage_list_menu_two_line_title_color })
                            setDescriptionColor(VortexSettings.colors { key_storage_list_menu_two_line_description_color })
                            setRippleColor(VortexSettings.colors { key_storage_list_menu_two_line_ripple_color })
                            setBackgroundColor(VortexSettings.colors { key_storage_list_menu_two_line_surface_color })
                        }

                    Items.DIVIDER ->
                        DividerItemView(parent.context).apply {
                            setColor(VortexSettings.colors { key_storage_list_menu_divider_color })
                        }

                    Items.DRAWER ->
                        DrawerItemView(parent.context).apply {
                            setTitleColor(VortexSettings.colors { key_storage_list_menu_drawer_title_color })
                            setIconColor(VortexSettings.colors { key_storage_list_menu_drawer_icon_color })
                            setRippleColor(VortexSettings.colors { key_storage_list_menu_drawer_ripple_color })
                            setBackgroundColor(VortexSettings.colors { key_storage_list_menu_drawer_surface_color })
                        }

                    Items.TITLE ->
                        TitleItemView(context).apply {
                            setTitleColor(VortexSettings.colors { key_storage_list_menu_title_color })
                        }

                    else -> throw UnsupportedViewTypeException(viewType)
                }
            },
        )

    override fun onApplyRecyclerView(recycler: RecyclerView) {
        super.onApplyRecyclerView(recycler)
        recycler.frameParams(MATCH_PARENT, WRAP_CONTENT) {
            gravity = Gravity.BOTTOM
        }
        recycler.background =
            RoundedCornerDrawable(
                color = VortexSettings.colors { key_storage_list_menu_background_color },
                topLeft = context.dp(16F),
                topRight = context.dp(16F),
            )
    }

    override fun onPrepareImpl() {
        if (repository == null) {
            repository =
                context.findDependencies<StorageListDependencies>().repository
        }
        args?.let { items ->
            adapter.replace(buildMenu(items))
        }
    }

    override fun onFocusImpl() {
    }

    override fun onHideImpl() {
        scope.cancel()
    }

    override fun onDestroyImpl() {
        super.onDestroyImpl()
    }

    override fun onSaveImpl(
        buffer: Bundle,
        prefix: String,
    ): Boolean = false

    override fun onRestoreImpl(
        buffer: Bundle,
        prefix: String,
    ): Boolean = false

    override fun onItemClick(
        view: View,
        position: Int,
    ) {
        when (view.id) {
            R.id.file_manager_list_menu_op_add ->
                args?.single()?.let { parent ->
                    router?.navigate(
                        StorageCreateItemScreenController(context),
                        ParentPath(parent),
                    )
                }

            R.id.file_manager_list_menu_op_swap -> {
            }

            R.id.file_manager_list_menu_op_move -> {
                val items = args ?: return
                scope.launch {
                    repository?.addPendingTransition(Transition.Move(items.map { item -> item.path }))
                    router?.navigateBack()
                }
            }

            R.id.file_manager_list_menu_op_copy -> {
                val items = args ?: return
                scope.launch {
                    repository?.addPendingTransition(Transition.Copy(items.map { it.path }))
                    router?.navigateBack()
                }
            }

            R.id.file_manager_list_menu_op_rename -> {
                args?.let { items ->
                    router?.navigate(
                        StorageRenameItemScreenController(context),
                        items.single(),
                    )
                }
            }

            R.id.file_manager_list_menu_op_delete ->
                args?.let { items ->
                    router?.navigate(
                        StorageTransactionScreenController(context),
                        StorageTransactionScreenController.Args.Modification(
                            items,
                            LOAD_TYPE_DELETE,
                        ),
                    )
                }

            R.id.file_manager_list_menu_detail -> {
                args?.let { items ->
                    router?.navigate(
                        StorageItemDetailScreenController(context),
                        PathItem(items.single()),
                    )
                }
            }
        }
    }

    override fun onLongItemClick(
        view: View,
        position: Int,
    ): Boolean = false
}
